// src/components/todo.tsx

"use client"
import { useEffect, useState } from "react"
import { remult,FormEvent } from "remult"
import { Task } from "../shared/Task"

const taskRepo = remult.repo(Task)

export default function Todo() {
  const [tasks, setTasks] = useState<Task[]>([])
  const [newTaskTitle, setNewTaskTitle] = useState("")

  const addTask = async (e: FormEvent) => {
    e.preventDefault()
    try {
      const newTask = await taskRepo.insert({ title: newTaskTitle })
      setTasks([...tasks, newTask])
      setNewTaskTitle("")
    } catch (error) {
      alert((error as { message: string }).message)
    }
  }

  useEffect(() => {
    taskRepo.find({
        limit: 2,
        orderBy: { createdAt: "desc" },
        where: {
            completed: true,        
        }
    }).then(setTasks)
  }, [])
  return (
    <div>
      <h1 className="text-3xl text-center text-red-500">Todos</h1>
      <main>
        {tasks.map((task) => {
          return (
            <div key={task.id}>
              <input type="checkbox" checked={task.completed} />
              {task.title}
            </div>
          )
        })}
      </main>
    </div>
  )
}